package com.yipao.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;

import java.util.Map;

/**
 * HttpClientUtil
 *
 * @author hebin
 */
@Slf4j
public class HttpClientUtil {

    /**
     * 简单的get请求
     * GET 请求指定的页面信息，并返回实体主体
     *
     * @throws IOException
     */
    public static String get(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            /**
             * 底层http链接仍由响应对象保存
             * 允许直接从网络套接字流式传输响应内容
             * 为了确保正确释放系统资源
             * 用户必须从finally子句中调用CloseableHttpResponse #close()
             */
            // 对响应主体做一些有用的事情
            // 并确保他完全被消耗掉
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            log.error("http get response", e);
            return null;
        }
    }


    /**
     * 简单的get请求
     * GET 请求指定的页面信息，并返回实体主体
     *
     * @throws IOException
     */
    public static String get(String url, Map<String, String> headerMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        if (!headerMap.isEmpty()) {
            headerMap.forEach(httpGet::setHeader);
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            /**
             * 底层http链接仍由响应对象保存
             * 允许直接从网络套接字流式传输响应内容
             * 为了确保正确释放系统资源
             * 用户必须从finally子句中调用CloseableHttpResponse #close()
             */
            // 对响应主体做一些有用的事情
            // 并确保他完全被消耗掉
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            log.error("http get response", e);
            return null;
        }
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param jsonParam
     * @return
     */
    public static String doPost(String url, Object jsonParam) {
        try {
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpClient client = HttpClients.createDefault();
            String respContent = null;
            // 解决中文乱码问题
            StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse resp = client.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                respContent = EntityUtils.toString(he, "UTF-8");
            } else {
                log.error("请求异常{}", EntityUtils.toString(resp.getEntity(), "UTF-8"));
            }
            return respContent;
        } catch (Exception e) {
            log.error("请求异常", e);
            return null;
        }
    }

    /**
     * jdk httpClient
     * @param url
     * @param type
     * @param param
     */
   /* public String send(String url, String type, Object param) {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request;
        if ("GET".equals(type)) {
            request = HttpRequest.newBuilder(URI.create(url)).GET().build();
        } else {
            request = HttpRequest.newBuilder(URI.create(url))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(param.toString())).build();
        }

        java.net.http.HttpResponse.BodyHandler<String> responseBodyHandler = java.net.http.HttpResponse.BodyHandlers.ofString();
        java.net.http.HttpResponse<String> response;
        try {
            response = client.send(request, responseBodyHandler);
            return response.body();
        } catch (IOException e) {
            log.error("httpClient",e);
        } catch (InterruptedException e) {
            log.error("httpClient",e);
        }
        return null;
    }*/
}
